package com.gradledemo.controller;

import com.gradledemo.common.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/*
 * Copyright (c) 2010-2015 LiZaoNet Inc. (http://www.lizaonet.com).
 * license: http://www.lizaonet.com
 */

/**
 * Created by Charles.Tan on 2014/8/1.
 */
@Controller
public class IndexAction extends BaseAction {
    private static final Logger log = LogManager.getLogger(IndexAction.class.getName());

    @RequestMapping(value = "/index.htm", method = {RequestMethod.GET})
    public String index(Model model) {
        log.info("index");
        model.addAttribute("vale", "index");
        return "default/main/index";
    }

    @RequestMapping(value = "/404.htm", method = {RequestMethod.GET})
    public String pageNotFound() {
        return "default/common/404";
    }

    @RequestMapping(value = "/500.htm", method = {RequestMethod.GET})
    public String error() {
        return "default/common/500";
    }

    @RequestMapping(value = "/{message}.htm", method = {RequestMethod.GET})
    @ResponseBody
    public Integer changeLocal(
            @PathVariable(value = "message") String message,
            HttpServletRequest request
    ) {
        log.info("locale= {}", message);
        int result = 2;
        if (Constant.localeMap.containsKey(message)) {
            Locale locale = Constant.localeMap.get(message);
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
            result = 1;
        }
        return result;
    }
}
